package com.tangly.module.controller;

import com.tangly.common.base.BaseController;
import com.tangly.common.shiro.AuthInfo;
import com.tangly.common.shiro.jwt.JWTUtil;
import com.tangly.module.entity.SysPermission;
import com.tangly.module.entity.SysRole;
import com.tangly.module.entity.UserAuth;
import com.tangly.module.service.ISysPermissionService;
import com.tangly.module.service.ISysRoleService;
import com.tangly.module.service.IUserAuthService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tangly
 */
@RestController
@RequestMapping(value = "/auth")
@Api(description = "授权认证控制器", tags = "授权认证模块")
public class AuthController extends BaseController {

    @Autowired
    private IUserAuthService iUserAuthService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private ISysPermissionService iSysPermissionService;

    @PostMapping(value = "/getAuthInfo")
    public AuthInfo getAuthInfo(@RequestParam(value = "jwt", required = false) String jwt) {
        if (StringUtils.isEmpty(jwt)) {
            throw new UnauthenticatedException();
        }
        Long authId = JWTUtil.getUserAuthId(jwt);
        Long userInfoId = JWTUtil.getUserInfoId(jwt);
        UserAuth userAuth = iUserAuthService.getUserAuthById(authId);
        List<SysRole> sysRoles = iSysRoleService.getSysRole(userInfoId);
        List<SysPermission> sysPermissions = iSysPermissionService.getPermissionList(userInfoId);

        List<String> permissions = new ArrayList<>();
        for (SysPermission p : sysPermissions) {
            permissions.add(p.getName());
        }

        List<String> roles = new ArrayList<>();
        for (SysRole r : sysRoles) {
            roles.add(r.getName());
        }

        AuthInfo authInfo = AuthInfo.builder()
                .userAuthId(userAuth.getId())
                .userId(userInfoId)
                .username(userAuth.getLoginAccount())
                .password(userAuth.getLoginPassword())
                .permissions(permissions)
                .roles(roles)
                .build();

        return authInfo;

    }
}
